<?php

namespace App\Http\Controllers\Admin;

use App\Models\ContestActivity;
use App\Models\ContestActivityDeclare;
use App\Validate\ContestActivityDeclareValidate;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛活动原创申明  （线上大赛 原创申明   原创申请，只在2个地方配置；1.创建大赛 2.单位管理）
 * Class ContestType   
 * @package app\admin\controller        这里弃用
 */
class ContestActivityDeclareController extends CommonController
{
    public $model = null;
    public $contestModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ContestActivityDeclare();
        $this->contestModel = new ContestActivity();
        $this->validate = new ContestActivityDeclareValidate();
    }

    /**
     * 原创申明详情
     * @param id int 比赛id
     * @param lib_id int 独立活动无此参数，非独立活动必须
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return  $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->contestModel->where('id', $this->request->id)->first();
        if (empty($res)) {
            return $this->returnApi(202, "大赛不存在");
        }
        if ($res->node == 2 && empty($this->request->lib_id)) {
            return $this->returnApi(202, "图书馆id不能为空");
        }

        $result = $this->model->detail($this->request->id, $this->request->lib_id);
        if (empty($result)) {
            return $this->returnApi(203, "暂无数据");
        }
        return $this->returnApi(200, "查询成功", true, $result->toArray());
    }

    /**
     * 修改
     * @param id int 比赛id
     * @param lib_id int 图书馆id
     * @param content string 内容名称  可为空  空为删除
     */
    public function change()
    {
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $res = $this->contestModel->where('id', $this->request->id)->first();
        if (empty($res)) {
            return $this->returnApi(202, "大赛不存在");
        }
        if ($res->node == 1 && empty($this->request->lib_id)) {
            return $this->returnApi(202, "图书馆id不能为空");
        }

        DB::beginTransaction();
        try {
            $this->model->change($this->request->all());

            DB::commit();
            return $this->returnApi(200, "设置成功", true);
        } catch (\Exception $e) {

            DB::rollBack();
            return $this->returnApi(202, "设置失败");
        }
    }
}
